import {routerRedux} from 'dva/router';
import {message} from 'antd';
import {userGroupList, userList, userGroup, addUserGroup} from '../services/api';

export default {
  namespace: 'userList',
  state: {
    data: [],
    discountData: {}, //促销数据
    group: []
  },

  effects: {
    *fetchGroup({payload}, {call, put}){
      const res = yield call(userGroupList, payload);
      if (res) {
        yield put({
          type: 'save',
          payload: {group: res}
        });
      }
    },
    *fetch({payload}, {call, put}){
      const res = yield call(userList, payload);
      if (res) {
        yield put({
          type: 'save',
          payload: {data: res}
        });
      }
    },
    *userGroup({ payload }, { call, put }){
      const res = yield call(userGroup, payload);
      if(res){
        yield put({
          type: 'saveGroup',
          payload : payload
        });
        message.success('分组成功！');
      }
    },
    *addGroup({ payload }, { call, put }){
      const res = yield call(addUserGroup, payload);
      if(res){
        yield put({
          type: 'saveAddGroup',
          payload : res
        });
        message.success('新增成功！');
      }
    },
    // *changeStatus({ payload }, { call, put }){
    //   const res = yield call(discountList, payload);
    //   if(res){
    //     yield put({
    //       type : 'save',
    //       payload : {data : res}
    //     });
    //   }
    // },
    // *fetchData({ payload }, { call, put }){  //统计数据
    //   const res = yield call(getDiscountData, payload);
    //   if(res){
    //     yield put({
    //       type : 'save',
    //       payload : {discountData : res}
    //     });
    //   }
    // }
  },

  reducers: {
    save(state, {payload}){
      return {
        ...state,
        ...payload
      }
    },
    saveGroup(state, { payload }){
      let { ids, groups } = payload;
      ids = ids.split(',');
      groups = groups.split(',');
      console.log('a');
      let data = {...state.data};
      data.list.forEach(v=>{
        ids.forEach(val=>{
          if(v.id == val){  //id相等
            let temp = [];
            state.group.forEach(g=>{
              groups.forEach(gs=>{
                if(gs == g.name){
                  temp.push(g.name);
                }
              })
            });
            v.groups = temp;
          }
        });
      });
      return {
        ...state,
        ...{data : data}
      }
    },
    saveAddGroup(state, { payload }){
      let group = [...state.group];
      group.push(payload);
      return {
        ...state,
        group
      }
    },
  },
};
